package com.huixiaodian.baselibrary.utils;

import android.content.Context;

import com.huixiaodian.baselibrary.common.Config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class SSLContextUtil {

    public static SSLContext getSSLContext(Context context){
        CertificateFactory certificateFactory;
        InputStream inputStream;
        Certificate certificate ;
        KeyStore keyStore ;
        TrustManagerFactory trustManagerFactory;
        SSLContext sslContext ;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            if(SharedPreferencesUtil.getInstance(context).getLong(Config.SSL_START_USING_TIME) > 0){
                if(System.currentTimeMillis() >
                        ((SharedPreferencesUtil.getInstance(context).getLong(Config.SSL_START_USING_TIME)))){
                    inputStream = context.getAssets().open("DSLiang7.cer");
//                    if (new File(context.getFilesDir(),
//                            SharedPreferencesUtil.getInstance(context).getString(Config.SSL_SAVE_PATH)).exists()) {
//                        inputStream = new FileInputStream(new File(context.getFilesDir(),
//                                SharedPreferencesUtil.getInstance(context).getString(Config.SSL_SAVE_PATH)));
//                    } else {
//                        inputStream = context.getAssets().open("DSLiang7.cer");
//                    }
                }else{
                    inputStream = context.getAssets().open("DSLiang.cer");
                }
            }else{
                if(System.currentTimeMillis() > 1618847999000L){
                    inputStream = context.getAssets().open("DSLiang7.cer");
                }else{
                    inputStream = context.getAssets().open("DSLiang.cer");
                }
            }
            try{
                certificate = certificateFactory.generateCertificate(inputStream);
            }finally {
                inputStream.close();
            }
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
            keyStore.setCertificateEntry("mykey", certificate);
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext;
        } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException exception) {
            exception.printStackTrace();
        }
        return null;
    }

    public static boolean isNeedLoadCerFile(Context context, String filePath) {
        File fileDir = context.getFilesDir();
        File cerFile = new File(fileDir, filePath);
        if(!cerFile.exists()){
            return true;
        }else{
            InputStream inputStream = null;
            try  {
                inputStream = new FileInputStream(cerFile);
                X509Certificate certificate = (X509Certificate)
                        (CertificateFactory.getInstance("X.509")
                                .generateCertificate(inputStream));
                Date afterDate = certificate.getNotAfter();
                return !new Date().before(afterDate);
            }catch (FileNotFoundException | CertificateException exception){
                exception.printStackTrace();
                return true;
            }finally {
                try{
                    if(inputStream != null) inputStream.close();
                }catch ( IOException exception){
                    exception.printStackTrace();
                }
            }
        }
    }
}
